package com.android.personal.kotlin.control;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by zhangwentao on 2016/12/14.
 */

public class WatchedImp implements Watched {

    private static volatile WatchedImp mDataChangeWatched;

    private Set<Watcher> mOnDataChangeWatcherList = new HashSet<>();

    private WatchedImp() {}

    public static WatchedImp getInstance() {
        if (mDataChangeWatched == null) {
            synchronized (WatchedImp.class) {
                if (mDataChangeWatched == null) {
                    mDataChangeWatched = new WatchedImp();
                }
            }
        }
        return mDataChangeWatched;
    }

    @Override
    public void addWatcher(Watcher watcher) {
        synchronized (mOnDataChangeWatcherList) {
            mOnDataChangeWatcherList.add(watcher);
        }
    }

    @Override
    public void removeWatcher(Watcher watcher) {
        synchronized (mOnDataChangeWatcherList) {
            mOnDataChangeWatcherList.remove(watcher);
        }
    }

    @Override
    public void notifyWatchers(IssueKey string, Object o) {
        for (Watcher dataChangeWatcher : mOnDataChangeWatcherList) {
            dataChangeWatcher.onDataChanged(string, o);
        }
    }
}
